/**
 * 
 */
package com.cqan.service.account.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.cqan.entity.account.Permission;
import com.cqan.entity.account.Role;
import com.cqan.entity.account.User;
import com.cqan.service.account.UserService;

/**
 * @author wuhui
 *
 * 上午10:16:00
 */
@Service("userDetailsService")
public class UserDetailServiceImpl implements UserDetailsService {

	private UserService userService;
	
	@Override
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		
		System.out.println("loginName is " + username);  
        User user = this.userService.findBy("loginName",username);  
        if(user == null) {  
            throw new UsernameNotFoundException(username);  
        }  
        List<GrantedAuthority> grantedAuths = obtionGrantedAuthorities(user);  
        user.setAuthorities(Collections.unmodifiableList(grantedAuths));
        return user;  
	}
	
	
	
	//取得用户的权限  
    private List<GrantedAuthority> obtionGrantedAuthorities(com.cqan.entity.account.User user) {  
    	List<GrantedAuthority> authSet = new ArrayList<GrantedAuthority>();  
        List<Role> roles = user.getRoles();  
          
        for(Role role : roles) {  
            List<Permission> tempRes = role.getPermissions();  
            for(Permission res : tempRes) {  
                authSet.add(new GrantedAuthorityImpl(res.getCode()));  
           }  
        }  
        return authSet;  
    }  

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	

}
